package com.lczc.soa.controller;

import com.lczc.soa.domain.Area;
import com.lczc.soa.domain.SearchStreetResponse;
import com.lczc.soa.domain.Street;
import com.lczc.soa.service.AreaService;
import com.lczc.soa.service.StreetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/Street")
public class StreetController {

    @Autowired
    private StreetService streetService;

    @Autowired
    private AreaService areaService;

    @RequestMapping("/toadd")
    public String addStreetPage(Model model){
        model.addAttribute("street",new Street());
        List<Area> areas = areaService.listArea();
        model.addAttribute("areas",areas);
        return "street_add";
    }

    @RequestMapping("/add")
    public String addStreet(Street street){
        int updated = streetService.saveStreet(street);
        System.out.println(street.getAreaId());
        System.out.println(street.getStreetName());
        return "redirect:/Street/list";
    }

    @RequestMapping("/list")
    public String StreetList(){
        return "street_list";
    }

    @GetMapping("/api/search")
    @ResponseBody
    public SearchStreetResponse searchStreetResponse(@RequestParam("pageNum") Integer pageNum,
                                                 @RequestParam("pageSize") Integer pageSize){
        return streetService.findAllStreet(pageNum,pageSize);
    }

    @GetMapping("/api/searchLike")
    @ResponseBody
    public SearchStreetResponse searchStreetResponseLike(@RequestParam("keywords") String keywords,
                                                     @RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("pageSize") Integer pageSize){
        return streetService.findStreetLikeName(keywords,pageNum,pageSize);
    }

    @RequestMapping("/edit")
    public String EditStreet(@RequestParam("id") String id, Model model){
        Street street = streetService.findStreetByPrimaryKey(id);
        model.addAttribute("street",street);
        List<Area> areas = areaService.listArea();
        model.addAttribute("areas",areas);
        return "street_add";
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteStreet(@RequestParam("id") String id){
        int deleted = streetService.deleteStreet(id);
        return deleted > 0;
    }

}
